package org.xwalk.core.internal;


import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class XWalkJavascriptResultHandlerBridge extends XWalkJavascriptResultHandlerInternal {
    private XWalkCoreBridge coreBridge;
    private Object wrapper;

    public Object getWrapper() {
        return wrapper;
    }


    private XWalkJavascriptResultHandlerInternal internal;

    XWalkJavascriptResultHandlerBridge(XWalkJavascriptResultHandlerInternal internal) {
        this.internal = internal;
        reflectionInit();
    }

    @Override
    public void confirm() {
        if (confirmMethod == null || confirmMethod.isNull()) {
            confirmSuper();
        } else {
            confirmMethod.invoke();
        }
    }

    public void confirmSuper() {
        if (internal == null) {
            super.confirm();
        } else {
            internal.confirm();
        }
    }

    private ReflectMethod confirmMethod = new ReflectMethod(null, "confirm");

    @Override
    public void confirmWithResult(final String promptResult) {
        if (confirmWithResultStringMethod == null || confirmWithResultStringMethod.isNull()) {
            confirmWithResultSuper(promptResult);
        } else {
            confirmWithResultStringMethod.invoke(promptResult);
        }
    }

    public void confirmWithResultSuper(final String promptResult) {
        if (internal == null) {
            super.confirmWithResult(promptResult);
        } else {
            internal.confirmWithResult(promptResult);
        }
    }

    private ReflectMethod confirmWithResultStringMethod = new ReflectMethod(null, "confirmWithResult");

    @Override
    public void cancel() {
        if (cancelMethod == null || cancelMethod.isNull()) {
            cancelSuper();
        } else {
            cancelMethod.invoke();
        }
    }

    public void cancelSuper() {
        if (internal == null) {
            super.cancel();
        } else {
            internal.cancel();
        }
    }

    private ReflectMethod cancelMethod = new ReflectMethod(null, "cancel");


    void reflectionInit() {
        coreBridge = XWalkCoreBridge.getInstance();
        if (coreBridge == null) return;

        ReflectConstructor constructor = new ReflectConstructor(
                coreBridge.getWrapperClass("XWalkJavascriptResultHandler"), Object.class);
        try {
            wrapper = constructor.newInstance(this);
        } catch (UnsupportedOperationException e) {
            return;
        }

        confirmMethod.init(wrapper, null,
                "confirm");
        confirmWithResultStringMethod.init(wrapper, null,
                "confirmWithResult", String.class);
        cancelMethod.init(wrapper, null,
                "cancel");
    }
}
